
<script>
	import userCheck from './xilu/userCheck.js';
	import chatIM from './xilu/websocket.js';
	// #ifdef H5
	import h5Fix from '@/common/h5-fix.js';
	// #endif

	export default {
		onLaunch: function() {
			let app = this;

			// 全局挂载测试方法
			app.testPrivacyModal = () => {
				console.log('Manual test privacy modal');
				this.showCustomPrivacyModal('1.0.0');
			};

			// 全局挂载新的隐私政策测试方法
			app.testNewPrivacyModal = () => {
				console.log('Test new privacy modal with API');
				// 清除之前的同意记录进行测试
				uni.removeStorageSync('privacy_policy_agreed');
				uni.removeStorageSync('privacy_policy_version');
				this.checkPrivacyPolicy();
			};

			// #ifdef H5
			// 初始化H5兼容性修复
			h5Fix.init();
			console.log('H5 environment detected, privacy check will be performed in onReady');
			// #endif

			// 检查是否需要显示隐私政策弹窗 - 只在APP平台立即执行
			// #ifdef APP-PLUS
			console.log('APP-PLUS environment detected, checking privacy policy');
			setTimeout(() => {
				this.checkPrivacyPolicy();
				this.hasCheckedPrivacy = true;
			}, 100);
			// #endif

			if (app.globalData.primary != 'blue') {
				uni.setNavigationBarColor({
					frontColor: '#ffffff',
					backgroundColor: '#2FC971',
					animation: {
						duration: 300
					},
					success: (ret) => {
						console.log(ret);
					},
					fail(err) {
						console.log(err);
					}
				})
			} else {
				uni.setNavigationBarColor({
					frontColor: '#ffffff',
					backgroundColor: '#2FC971',
					animation: {
						duration: 300
					},
				})
			}
			app.$core.onRequestComplete(function(ret, response) {
				if (ret && ret.code === 401) {
					if (app.$core.getUserinfo()) {
						app.$core.logout();
						uni.navigateTo({
							url: '/pages/public/login'
						});
						uni.showToast({
							title: '登录过期,请重新登录',
							icon: 'none'
						});
					}
				}
			});
			setTimeout(function() {
				// app初始化完成后再执行
				let userinfo = app.$core.getUserinfo();
				console.log('App.vue onLaunch - 获取用户信息:', userinfo ? '已登录' : '未登录');
				if (userinfo) {
					app.globalData.userinfo = userinfo;
					console.log('App.vue onLaunch - 准备连接WebSocket...');
					chatIM.connectSocket();

					// 使用全局用户信息检测模块
					if (userCheck.checkUserInfo(app)) {
						userCheck.navigateToUserInfoVerify();
					}
				}
				if(userinfo && userinfo.group_id == 2 && userinfo.group_model.audit_status != 1){
					//企业的身份时查询下状态
					app.$core.get({url: '/xilujob.company/company',loading: false,success(ret, data) {
						userinfo.group_model.audit_status = ret.data.userinfo.group_model.audit_status;
						app.$core.setUserinfo(userinfo);
					}
				});
				}
				
			}, 1);

		},
		onReady() {
			// #ifdef H5
			console.log('App onReady called, hasCheckedPrivacy:', this.hasCheckedPrivacy);
			// H5环境下，确保DOM完全加载后再检查隐私政策
			this.$nextTick(() => {
				console.log('nextTick executed, checking privacy policy');
				if (!this.hasCheckedPrivacy) {
					// 添加额外的延迟，确保所有依赖都加载完成
					setTimeout(() => {
						console.log('About to check privacy policy in H5');
						this.checkPrivacyPolicy();
						this.hasCheckedPrivacy = true;
					}, 500);
				} else {
					console.log('Privacy already checked, skipping');
				}
			});
			// #endif
		},
		data() {
			return {
				// 隐私政策相关数据
				hasCheckedPrivacy: false
			}
		},
		globalData: {
			//小程序配置的接口请求域名，为项目部署的服务器路径
			primary: 'orange', //两种主题（orange｜blue）
			color: '#2A79F2',
			appid: '',
			wsDomain: 'wss://admin.mosizp.cn:8301',
			// 开发环境使用相对路径，通过代理解决跨域；生产环境使用完整域名
			// #ifdef H5
			apiBaseUri: process.env.NODE_ENV === 'development' ? "/api" : "https://admin.mosizp.cn/api",
			// #endif
			// #ifndef H5
			apiBaseUri: "https://admin.mosizp.cn/api",
			// #endif
			////前端上传图片补全域名，如oss的https://xxxx.oss-cn-shanghai.aliyuncs.com，或https://your.site.com
			storageBaseUri: "https://admin.mosizp.cn",
			//阿里OSS的上传路径
			uploadOssStatus: false,
			alioss: {
				endpoint: 'https://admin.mosizp.cn'
			},
			Events: {
				ConfigChange: "configChange",
				UserLogin: "userLogin",
				UserLogout: "userLogout",
				UserinfoChange: 'userinfoChange',
				UserinfoUpdate: "userinfoUpdate",
				UserProfileUpdate: "userProfileUpdate",
				UcenterInfoCompleteChange: "ucenterInfoCompleteChange",
				CurrentCityChange: 'currentCityChange',
				CurrentDistrictChange: 'currentDistrictChange',
				JobCreate: "jobCreate",
				JobUpdate: "jobUpdate",
				JobDelete: "jobDelete",
				InterviewCommentAdd: "interviewCommentAdd",
				ResumeFavAdd: "resumeFavAdd",
				ResumeFavRemove: "resumeFavRemove",
				JobFavAdd: 'JobFavAdd',
				JobFavRemove: 'JobFavRemove',
				CompanyFavRemove: "companyFavRemove",
				CompanyFavAdd: "companyFavAdd",
				ClearMessageCount: "clearMessageCount",
				RefreshUserCenter: "refreshUserCenter", //设置refresh标记，回到usercenter后刷新页面

				WebsocketMessageCount: 'websocketMessageCount'
			},
			config: {
				logo: '',
				platform_name: '',
				customer_qrcode: '',
				user_agreement: 0,
				privacy_agreement: 0
			},
			chat_config: {
				SocketTask: null,
				Timer: null,
				ErrorMsg: [],
				MaxRetryCount: 30, // 最大重连次数
				CurrentRetryCount: 0,
				ortherdata: null, //其他通用数据
				emoList: [], //表情
				messageCount: 0, //未读消息数
			},
			location: {
				latitude: '',
				longitude: ''
			},
			defaultCity: {
				id: 821,
				name: '南京市',
			}

		},
		onShow: function(e) {
			// 全局token检查，确保用户登录状态有效
			this.$core.checkTokenValid();

			if (e.query) {
				if (e.query.scene) {
					let scene = decodeURIComponent(e.query.scene);
					let options = {}
					for (var i = 0; i < scene.split('&').length; i++) {
						var arr = scene.split('&')[i].split('=');
						options[arr[0]] = arr[1];
					}
					if (options.uid != 'undefined' && options.uid > 0) {
						try {
							uni.setStorageSync('recom_pid', options.uid);
						} catch (e) {
							//TODO handle the exception
							console.log(e);
						}

					}
					if (options.group != 'undefined') {
						try {
							uni.setStorageSync('recom_group', options.group)
						} catch (e) {
							//TODO handle the exception
							console.log(e);
						}
					
					}
				}

			}
		},
		onHide: function() {
			console.log('App Hide')
		},
		methods: {
			// 检查隐私政策是否已同意 - 只在APP和H5平台生效
			checkPrivacyPolicy() {
				// #ifdef APP-PLUS || H5
				console.log('checkPrivacyPolicy called');

				const privacyAgreed = uni.getStorageSync('privacy_policy_agreed');
				const agreedVersion = uni.getStorageSync('privacy_policy_version');
				const currentVersion = '1.0.0'; // 隐私政策版本号，更新隐私政策时修改此版本号

				console.log('Privacy check:', { privacyAgreed, agreedVersion, currentVersion });

				// 如果没有同意过隐私政策，或者隐私政策版本已更新
				if (!privacyAgreed || agreedVersion !== currentVersion) {
					console.log('Need to show privacy popup');
					// 先获取隐私政策内容，再显示弹窗
					this.fetchPrivacyPolicyContent(currentVersion);
				} else {
					console.log('Privacy policy already agreed');
				}
				// #endif
			},

			// 获取隐私政策内容
			fetchPrivacyPolicyContent(version) {
				// #ifdef APP-PLUS || H5
				const app = this;
				app.$core.get({
					url: '/xilujob.user/help_detail/id/4',
					loading: false,
					success(ret, data) {
						if (ret.code === 1 && ret.data) {
							// 显示包含隐私政策内容的弹窗
							app.showPrivacyPopupWithContent(version, ret.data.title, ret.data.content);
						} else {
							// 如果获取失败，显示默认弹窗
							app.showPrivacyPopup(version);
						}
					},
					fail() {
						// 如果获取失败，显示默认弹窗
						app.showPrivacyPopup(version);
					}
				});
				// #endif
			},

			// 显示隐私政策弹窗 - 只在APP和H5平台生效
			showPrivacyPopup(version) {
				// #ifdef APP-PLUS || H5
				console.log('showPrivacyPopup called with version:', version);
				this.showCustomPrivacyModal(version);
				// #endif
			},

			// 显示带有内容的隐私政策弹窗
			showPrivacyPopupWithContent(version, title, content) {
				// #ifdef APP-PLUS || H5
				console.log('showPrivacyPopupWithContent called with version:', version);

				// 直接创建包含完整内容的隐私政策弹窗
				this.createPrivacyModal(version, title, content);
				// #endif
			},

			// 创建隐私政策弹窗
			createPrivacyModal(version, title, content) {
				// #ifdef APP-PLUS || H5
				const app = this;

				// 清理HTML标签并保留文本内容，展示关键信息
				const cleanContent = content ?
					content.replace(/<[^>]*>/g, '').replace(/\s+/g, ' ').trim().substring(0, 800) :
					'为了更好地保护您的个人信息和隐私，我们制定了详细的隐私政策。我们承诺严格保护您的个人信息安全，不会在未经您同意的情况下收集、使用或分享您的个人信息。我们会采用合理的技术和管理措施保护您的个人信息安全。';

				uni.showModal({
					title: title || '隐私政策',
					content: `欢迎使用摩师直聘！\n\n${cleanContent}\n\n请您仔细阅读以上隐私政策内容，点击"同意并继续"表示您已阅读并同意我们的隐私政策。`,
					confirmText: '同意并继续',
					cancelText: '暂不使用',
					success: (res) => {
						if (res.confirm) {
							// 用户同意隐私政策
							app.handlePrivacyAgree(version);
						} else if (res.cancel) {
							// 用户拒绝隐私政策
							app.handlePrivacyDisagree();
						}
					}
				});
				// #endif
			},


			// 显示自定义隐私政策弹窗
			showCustomPrivacyModal(version) {
				// #ifdef APP-PLUS || H5
				console.log('showCustomPrivacyModal called with version:', version);

				try {
					// 直接在弹窗中展示隐私政策内容
					uni.showModal({
						title: '服务协议与隐私政策',
						content: '欢迎使用摩师直聘！\n\n为了更好地保护您的个人信息和隐私，我们制定了详细的隐私政策。我们承诺严格保护您的个人信息安全，不会在未经您同意的情况下收集、使用或分享您的个人信息。\n\n请您仔细阅读并同意我们的服务协议与隐私政策后继续使用。',
						confirmText: '同意并继续',
						cancelText: '暂不使用',
						success: (res) => {
							console.log('Modal success callback:', res);
							if (res.confirm) {
								// 用户同意隐私政策
								this.handlePrivacyAgree(version);
							} else if (res.cancel) {
								// 用户拒绝隐私政策
								this.handlePrivacyDisagree();
							}
						},
						fail: (err) => {
							console.error('Modal failed:', err);
						}
					});
				} catch (error) {
					console.error('Error calling uni.showModal:', error);
				}
				// #endif
			},



			// 处理隐私政策同意
			handlePrivacyAgree(version) {
				// #ifdef APP-PLUS || H5
				console.log('handlePrivacyAgree called with version:', version);

				// 保存同意记录
				uni.setStorageSync('privacy_policy_agreed', true);
				uni.setStorageSync('privacy_policy_version', version);
				uni.setStorageSync('privacy_policy_agreed_time', new Date().toISOString());

				uni.showToast({
					title: '感谢您的同意',
					icon: 'success'
				});
				// #endif
			},

			// 处理隐私政策拒绝
			handlePrivacyDisagree() {
				// #ifdef APP-PLUS || H5
				uni.showModal({
					title: '提示',
					content: '您需要同意隐私政策才能使用本应用',
					confirmText: '重新考虑',
					cancelText: '退出应用',
					success: (res) => {
						if (res.confirm) {
							// 用户选择重新考虑，再次显示隐私政策
							setTimeout(() => {
								this.showCustomPrivacyModal('1.0.0');
							}, 500);
						} else if (res.cancel) {
							// 退出应用
							// #ifdef APP-PLUS
							plus.runtime.quit();
							// #endif
							// #ifdef H5
							window.close();
							// #endif
						}
					}
				});
				// #endif
			}
		}
	}
</script>

<style lang="scss">
	@import "@/static/css/global.css";
	@import "@/uni_modules/uview-ui/index.scss";


	/* #ifdef APP-PLUS  || H5*/


	/deep/ .p_swiper .uni-swiper-dots {
		// 指示点整个区域
		right: 0;
		width: auto;
		left: auto;
	}

	/deep/ .find_swiper .uni-swiper-dots {
		// 指示点整个区域
		bottom: 62rpx;
	}

	.find_swiper .uni-swiper-dot-active {
		width: 30rpx;
		height: 15rpx;
		background: #FFFFFF;
		border-radius: 8rpx;
	}

	/* #endif */
	/* #ifdef MP-WEIXIN */

	.p_swiper .wx-swiper-dots.wx-swiper-dots-horizontal {

		right: 0;
		width: auto;
		left: auto;
	}

	.find_swiper .wx-swiper-dots.wx-swiper-dots-horizontal {
		bottom: 62rpx;

	}

	.find_swiper .wx-swiper-dot-active {
		width: 30rpx;
		height: 15rpx;
		background: #FFFFFF;
		border-radius: 8rpx;
	}

	/* #endif */
</style>